package main

import (
	"fmt"
	"strconv"
)

type Phone interface {
	call()
}

type Shape interface {
	area() float64
}

type IPhone struct {
	name string
}

type Action interface {
	move()
	// say()
}

type dog struct {
	name string
}

func (d dog) move() {
	d.name = "heihei"
	fmt.Println(d.name + "会动")
}

func (d *dog) say() {
	d.name = "heihei2"
	fmt.Println(d.name + "会说话")
}

func (phone IPhone) call() {
	fmt.Printf("I am %v, I can call you \n", phone.name)
}

type MiPhone struct {
	name string
}

func (phone MiPhone) call() {
	fmt.Printf("I am %v, I can call you \n", phone.name)
}

type Rectangle struct {
	width  float64
	height float64
}

func (r Rectangle) area() float64 {
	return r.height * r.width
}

type Circle struct {
	radius float64
}

func (c Circle) area() float64 {
	return 3.14 * c.radius * c.radius
}

func main() {
	fmt.Println("其他Go语言特性语法")

	/*接口（interface）*/
	var phone Phone
	phone = IPhone{"apple"}
	phone.call()
	phone = MiPhone{"xiaomi"}
	phone.call()

	var s Shape
	s = Rectangle{width: 10, height: 11}
	fmt.Println("矩形面积：", s.area())
	s = Circle{radius: 10}
	s.area()
	fmt.Println("三角形面积：", s.area())

	var ac Action
	wangcai := dog{"wangcai"}
	ac = wangcai
	ac.move()
	// ac.say()

	fugui := dog{"fugui"}
	ac = &fugui
	ac.move()
	fugui.say()

	/*类型转换（数值、字符串、接口）*/
	var sum int = 17
	var count int = 5
	var mean float32
	mean = float32(sum) / float32(count)
	fmt.Printf("mean 的值为: %f\n", mean)

	// strconv函数（字符串转换）
	str := "123"
	num, err := strconv.Atoi(str)
	if err != nil {
		fmt.Println("转换错误:", err)
	} else {
		fmt.Printf("字符串 '%s' 转换为整数为：%d\n", str, num)
	}

	// interface 转换（类似于Java的多态）
	var i interface{} = "Hello, World"
	str, ok := i.(string)
	if ok {
		fmt.Printf("'%s' is a string\n", str)
	} else {
		fmt.Println("conversion failed")
	}

	var a Phone = IPhone{"apple"}
	aa := a.(IPhone)
	aa.name = "apple care"
	fmt.Println(aa.name)

	/*错误处理*/
	// 正常情况
	if result, errorMsg := Divide(100, 10); errorMsg == "" {
		fmt.Println("100/10 = ", result)
	}
	// 当除数为零的时候会返回错误信息
	if _, errorMsg := Divide(100, 0); errorMsg != "" {
		fmt.Println("errorMsg is: ", errorMsg)
	}

}

// 定义一个 DivideError 结构
type DivideError struct {
	dividee int
	divider int
}

// 实现 `error` 接口
func (de *DivideError) Error() string {
	strFormat := `
    Cannot proceed, the divider is zero.
    dividee: %d
    divider: 0
`
	return fmt.Sprintf(strFormat, de.dividee)
}

// 定义 `int` 类型除法运算的函数
func Divide(varDividee int, varDivider int) (result int, errorMsg string) {
	if varDivider == 0 {
		dData := DivideError{
			dividee: varDividee,
			divider: varDivider,
		}
		errorMsg = dData.Error()
		return
	} else {
		return varDividee / varDivider, ""
	}

}
